package com.example.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import com.example.project.common.Result;
import com.example.project.entity.User;
import com.example.project.entity.Image;
import com.example.project.mapper.UserMapper;
import com.example.project.mapper.ImageMapper;
import com.example.project.service.AdminService;
import com.example.project.dto.UpdateUserRequest;
import com.example.project.dto.UpdatePasswordRequest;
import com.example.project.dto.UpdateProfileRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result<?> getNormalUserList(Integer page, Integer pageSize, String query, 
                                     Integer status, Long adminId) {
        if (!isAdmin(adminId)) {
            return Result.error("无权限访问");
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询普通用户
        queryWrapper.eq(User::getRoleId, 2L);
        
        if (StringUtils.hasText(query)) {
            queryWrapper.and(wrapper -> wrapper
                .like(User::getUsername, query)
                .or()
                .like(User::getEmail, query)
                .or()
                .like(User::getPhone, query));
        }
        
        if (status != null) {
            queryWrapper.eq(User::getStatus, status);
        }
        
        queryWrapper.orderByDesc(User::getCreatedAt);
        
        Page<User> userPage = new Page<>(page, pageSize);
        userMapper.selectPage(userPage, queryWrapper);
        
        return Result.success(userPage);
    }

    @Override
    public Result<?> getMerchantList(Integer page, Integer pageSize, String query, 
                                   Integer status, Long adminId) {
        if (!isAdmin(adminId)) {
            return Result.error("无权限访问");
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询商家
        queryWrapper.eq(User::getRoleId, 3L);
        
        if (StringUtils.hasText(query)) {
            queryWrapper.and(wrapper -> wrapper
                .like(User::getUsername, query)
                .or()
                .like(User::getEmail, query)
                .or()
                .like(User::getPhone, query));
        }
        
        if (status != null) {
            queryWrapper.eq(User::getStatus, status);
        }
        
        queryWrapper.orderByDesc(User::getCreatedAt);
        
        Page<User> userPage = new Page<>(page, pageSize);
        userMapper.selectPage(userPage, queryWrapper);
        
        return Result.success(userPage);
    }

    @Override
    public Result<?> getUserDetail(Long userId, Long adminId) {
        if (!isAdmin(adminId)) {
            return Result.error("无权限访问");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        return Result.success(user);
    }

    @Override
    @Transactional
    public Result<?> updateUser(Long userId, UpdateUserRequest request, Long adminId) {
        if (!isAdmin(adminId)) {
            return Result.error("无权限访问");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 检查用户名是否已存在
        if (StringUtils.hasText(request.getUsername())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, request.getUsername())
                    .ne(User::getId, userId);
            if (userMapper.selectOne(queryWrapper) != null) {
                return Result.error("用户名已存在");
            }
            user.setUsername(request.getUsername());
        }

        // 更新其他信息
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }
        if (request.getRoleId() != null) {
            user.setRoleId(request.getRoleId());
        }
        if (request.getStatus() != null) {
            user.setStatus(request.getStatus());
        }

        userMapper.updateById(user);
        return Result.success(null);
    }

    @Override
    @Transactional
    public Result<?> deleteUser(Long userId, Long adminId) {
        if (!isAdmin(adminId)) {
            return Result.error("无权限访问");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 检查是否是管理员
        if (user.getRoleId() == 1L) {
            return Result.error("不能删除管理员账号");
        }

        try {
            // 先删除用户相关的图片
            LambdaQueryWrapper<Image> imageWrapper = new LambdaQueryWrapper<>();
            imageWrapper.eq(Image::getUserId, userId);
            imageMapper.delete(imageWrapper);
            
            // 再删除用户
            userMapper.deleteById(userId);
            
            return Result.success(null);
        } catch (Exception e) {
            log.error("Delete user failed: ", e);
            throw new RuntimeException("删除用户失败");
        }
    }

    @Override
    public Result<?> updateUserStatus(Long userId, Integer status, Long adminId) {
        if (!isAdmin(adminId)) {
            return Result.error("无权限访问");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        user.setStatus(status);
        userMapper.updateById(user);
        
        return Result.success(null);
    }

    @Override
    public Result<?> updatePassword(Long userId, UpdatePasswordRequest request) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证旧密码
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            return Result.error("旧密码错误");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userMapper.updateById(user);
        
        return Result.success(null);
    }

    @Override
    public Result<?> getProfile(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        return Result.success(user);
    }

    @Override
    public Result<?> updateProfile(Long userId, UpdateProfileRequest request) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 检查用户名是否已存在
        if (StringUtils.hasText(request.getUsername())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, request.getUsername())
                    .ne(User::getId, userId);
            if (userMapper.selectOne(queryWrapper) != null) {
                return Result.error("用户名已存在");
            }
            user.setUsername(request.getUsername());
        }

        // 更新其他信息
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }
        if (StringUtils.hasText(request.getAvatarUrl())) {
            user.setAvatarUrl(request.getAvatarUrl());
        }

        userMapper.updateById(user);
        return Result.success(null);
    }

    @Override
    public Result<?> updateUserRole(Long userId, Long roleId, Long adminId) {
        if (!isAdmin(adminId)) {
            return Result.error("无权限访问");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 验证角色ID是否有效（1-管理员，2-普通用户，3-商家）
        if (roleId != 1L && roleId != 2L && roleId != 3L) {
            return Result.error("无效的角色ID");
        }

        user.setRoleId(roleId);
        userMapper.updateById(user);
        
        return Result.success(null);
    }

    // 验证是否是管理员
    private boolean isAdmin(Long userId) {
        User admin = userMapper.selectById(userId);
        return admin != null && admin.getRoleId() == 1L;
    }
}